package com.michaelbulava.TFS.actions;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.AbstractVcsHelper;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.FileStatusManager;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcsUtil.VcsUtil;
import com.michaelbulava.TFS.Messages;
import com.michaelbulava.TFS.vcs.TFSVcs;
import com.michaelbulava.TFS.vcs.exceptions.NotConnectedToTFS;
import com.michaelbulava.TFS.vcs.utils.TFSFileUtil;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by MichaelA on 8/20/2015.
 */
public class AddAction extends AnAction implements DumbAware {

    /**
     * Implement this method to provide your action handler.
     *
     * @param e Carries information on the invocation place
     */
    @Override
    public void actionPerformed(AnActionEvent e) {
        final Project project = (Project)e.getData(CommonDataKeys.PROJECT);
        final VirtualFile[] files = VcsUtil.getVirtualFiles(e);

        final List<VcsException> errors = new ArrayList();

        boolean result = ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
            @Override
            public void run() {
                errors.addAll(TFSVcs.getInstance(project).getCheckinEnvironment()
                        .scheduleUnversionedFilesForAddition(Arrays.asList(files)));
            }
        }, files.length > 1 ? Messages.getString("AddAction.AddAction.ProgressTitle_Single") :
                        Messages.getString("AddAction.ProgressTitle_Multiple"), false, project);

        if (!errors.isEmpty())
            AbstractVcsHelper.getInstance(project).showErrors(errors, TFSVcs.VCS_NAME);
    }

    @Override
    public void update(AnActionEvent e){
        Project project = (Project)e.getData(CommonDataKeys.PROJECT);
        VirtualFile[] files = VcsUtil.getVirtualFiles(e);
        e.getPresentation().setEnabled(isEnabled(project, files));
    }

    private static boolean isEnabled(Project project, VirtualFile[] files){
        if (files.length == 0)
            return false;
        FileStatusManager fileStatusManager = FileStatusManager.getInstance(project);
        for(VirtualFile file : files){
            if (!TFSVcs.getInstance(project).isModuleOnline(file))
                return false;
            if (fileStatusManager.getStatus(file) != FileStatus.UNKNOWN)
                return false;
        }
        return true;
    }


}
